package com.yizhilu.os.image.controller;

import com.google.gson.JsonObject;
import com.yizhilu.os.common.util.MyCORSFilter;
import com.yizhilu.os.core.controller.BaseController;
import com.yizhilu.os.core.util.DateUtils;
import com.yizhilu.os.core.util.PropertyUtil;
import com.yizhilu.os.core.util.web.HttpUtil;
import com.yizhilu.os.image.util.DocConverter;
import com.yizhilu.os.image.util.FileDownloadUtil;
import com.yizhilu.os.image.util.FileUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 上传文件控制器
 * @author:Steven
 * @date 2018/1/3 11:03
 */
@Controller
@RequestMapping("/upload")
public class UploadController{
     private static Logger logger = LoggerFactory.getLogger(UploadController.class);
    @RequestMapping(value={"/audio"}, method={org.springframework.web.bind.annotation.RequestMethod.OPTIONS})
    public void uploadAudio(HttpServletRequest request, HttpServletResponse response) {
        MyCORSFilter.dealUploadCors(request,response);
    }
    @RequestMapping(value = {"/audio"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> uploadAudio(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        Map<String,Object> result = new HashMap<>();
        try {
            uploadAudio(request,response);
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
            String[] paths = FileUtil.getSavePathByRequest(request);
            JsonObject json = FileUtil.saveAudio(file, paths);
            String path = json.get("url").getAsString();
            result.put("status",1);
            result.put("path",path);
            return result;
        } catch (Exception e) {
            result.put("status",0);
            result.put("msg","服务器异常！");
            logger.error("goswf error", e);
        }
        return result;
    }
  @RequestMapping({"/file"})
  @ResponseBody
  public Map<String,Object> uploadFile(HttpServletRequest request, HttpServletResponse response) {
    try {
          MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
          MultipartFile imgFile = multipartRequest.getFile("file");
          String[] paths = FileUtil.getSavePathByRequest(request,imgFile);
          JsonObject json = FileUtil.saveCommonFile(imgFile, paths);
          return getSuccessResult(json);
    }catch (Exception e){
        logger.error("uploadFile",e);
          return getException(e);
    }
  }
    private Map<String,Object> getSuccessResult(JsonObject json){
        Map<String,Object> result = new HashMap<>();
        if(json.get("error").getAsInt()==0){
            result.put("status","1");
            result.put("url",json.get("url").getAsString());
        }else{
            result.put("status","0");
            result.put("message",json.get("message").getAsString());
        }
        return result;
    }
    private Map<String,Object> getException(Exception e){
        Map<String,Object> result = new HashMap<>();
        result.put("status","0");
        result.put("message",e.getMessage());
        return result;
    }
    @RequestMapping(value={"/index"})
    @ResponseBody
    public String index(HttpServletRequest request, HttpServletResponse response) {
       return "idnex";
    }
    @RequestMapping({"/weixin/voice"})
    @ResponseBody
    public Map<String,Object> uploadWeixinVoice(HttpServletRequest request, HttpServletResponse response,String mediaId) {
        try {
            String res = HttpUtil.doGet(PropertyUtil.getInstance("project").getProperty("webPath")+"/weixin/login/getAccessToken",null);
            JSONObject jsonObject = JSONObject.fromObject(res);
            Map<String,Object> result = new HashMap<>();
            result.put("status","1");
            if("1".equals(jsonObject.get("status"))){
                String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+jsonObject.get("result")+"&media_id="+mediaId;
                StringBuilder urlPath = new StringBuilder(FileUtil.pathfix);
                urlPath.append(File.separator).append("sns/voiceLive")
                        .append(File.separator).append("amr").append(File.separator)
                        .append(DateUtils.toString(new Date(), "yyyyMMdd"));
                String amrName = FileUtil.getRandomFileNameString(".amr");
                String mp3Name =amrName.replace(".amr",".mp3");
                String amrSavePath = FileUtil.rootpath+urlPath;
                FileDownloadUtil.downLoadFromUrl(url,amrName,amrSavePath);
                String targetUrlPath = urlPath.toString().replace("amr","mp3")+File.separator+mp3Name;
                String mp3SavePath = FileUtil.rootpath+targetUrlPath;
                String sourceFile = amrSavePath+File.separator+amrName;
                FileUtil.changeToMp3(sourceFile,mp3SavePath);
                result.put("url","/"+targetUrlPath.toString() );
            }else{
                result.put("status","0");
            }
            return result;
        }catch (Exception e){
            logger.error("uploadFile",e);
            return getException(e);
        }
    }
}
